package Code;

import java.util.List;


public class Code2 {
    static class ListNode {
        int val;
        ListNode next;
        ListNode(int val) {
            this.val = val;
        }
    }
    static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);
        ListNode p = dummy;
        int carry = 0;
        while(l1 != null || l2 != null){
            int x = l1 == null? 0: l1.val;
            int y = l2 == null? 0: l2.val;
            int sum = x+y + carry;
            carry = sum/ 10;
            p.next = new ListNode(sum% 10);
            p = p.next;
            if( l1 != null) l1 = l1.next;
            if( l2 != null) l2 = l2.next;
        }
        return dummy.next;
    }
    public static void main(String[] args) {
        // 构建示例链表 1: 1 -> 2 -> 4
        ListNode list1 = new ListNode(2);
        list1.next = new ListNode(4);
        list1.next.next = new ListNode(3);

        // 构建示例链表 2: 1 -> 3 -> 4
        ListNode list2 = new ListNode(5);
        list2.next = new ListNode(6);
        list2.next.next = new ListNode(4);

        ListNode mergedList = addTwoNumbers(list1, list2);

        // 打印合并后的链表
        ListNode current = mergedList;
        while (current != null) {
            System.out.print(current.val + " ");
            current = current.next;
        }
    }
}
